﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using VTV.TaskManagementSystem.Common.Constant;
using VTV.TaskManagementSystem.Entities;
using ListItem = Ext.Net.ListItem;

namespace VTV.TaskManagementSystem.WebApp.Admin.Tasks
{
    public partial class List : System.Web.UI.Page
    {
        private static bool _isUpdate;
        private static int _taskID;
        private static string _taskName;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] == null || Session["UserName"] == null || Session["RoleLevel"] == null)
            {
                Response.Redirect("~/Admin/Login.aspx?return=/Admin/Tasks/List.aspx");
            }
        }

        protected void btnAdd_Click(object sender, DirectEventArgs e)
        {
            _isUpdate = false;
            this.windowDetailTask.Icon = Icon.ReportAdd;
            this.windowDetailTask.Title = "Thêm mới";
            this.windowDetailTask.Show();
        }

        protected void btnSave_Click(object sender, DirectEventArgs e)
        {
            var obj = new BusinessLogic.Task();
            var entityData = new Entities.Task
            {
                TaskID = !String.IsNullOrEmpty(this.TaskID.Text.Trim()) ? Convert.ToInt32(this.TaskID.Text) : 0,
                TaskName = String.IsNullOrEmpty(txtName.Text.Trim()) ? string.Empty : txtName.Text.Trim(),
                Descriptions = String.IsNullOrEmpty(txtNote.Text.Trim()) ? string.Empty : txtNote.Text.Trim()
            };

            if (_isUpdate)
            {
                var result = obj.Update(entityData);

                if (result)
                {
                    this.storeEmployee.Reload();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.UPDATE_SUCCESS_DETAIL_VN.Replace("{0}", txtName.Text)).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
            else
            {
                var result = obj.AddNew(entityData);

                if (result)
                {
                    this.storeEmployee.Reload();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.INSERT_SUCCESS_DETAIL_VN.Replace("{0}", txtName.Text)).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
        }

        protected void gridTask_OnCommand(object sender, DirectEventArgs e)
        {
            _taskID = Convert.ToInt32(e.ExtraParams["TaskID"]);
            var command = e.ExtraParams["Command"];

            if (command.Equals("Edit"))
            {
                _isUpdate = true;
                var obj = new BusinessLogic.Task();
                var entity = obj.GetTask(_taskID);

                if (entity != null && string.IsNullOrEmpty(obj.ErrorMessage))
                {
                    if (!this.SetValue(entity))
                    {
                        this.btnSave.Enable(false);
                        X.Msg.Notify(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.TRANSFER_FAILSE_VN + "<BR>" + AuditHelpMessage.PLS_BACK_LASTER).Show();
                    }
                }

                this.windowDetailTask.Icon = Icon.ReportEdit;
                this.windowDetailTask.Title = "Cập nhật thông tin";
                this.windowDetailTask.Show();
            }
            else
            {
                X.Msg.Confirm(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.DELETE_CONFIRM_VN,
                              new MessageBoxButtonsConfig()
                              {
                                  Yes = new MessageBoxButtonConfig
                                  {
                                      Text = "Xác nhận",
                                      Handler = "Task.List.DeleteEmployee()"
                                  },
                                  No = new MessageBoxButtonConfig
                                  {
                                      Text = "Quay lại"
                                  }

                              }).Show();
            }

        }

        protected void storeEmployee_OnReadData(object sender, StoreReadDataEventArgs e)
        {
            var start = e.Start;
            var limit = e.Limit;

            var source = new BusinessLogic.Task().GetAll(start, limit);
            var total = new BusinessLogic.Task().GetCount();

            if (source != null && source.Any() && total != null)
            {
                var data = new Paging<Entities.Task>(source, (int)total);

                e.Total = data.TotalRecords;

                this.storeEmployee.DataSource = data.Data;
                this.storeEmployee.DataBind();
            }
        }

        [DirectMethod(Namespace = "Task.List")]
        public void DeleteEmployee()
        {
            var obj = new BusinessLogic.Task();
            var entity = obj.GetTask(_taskID);
            if (entity != null && string.IsNullOrEmpty(obj.ErrorMessage))
            {
                var result = obj.Delete(entity);

                if (result)
                {
                    this.storeEmployee.Reload();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.DELETE_SUCCESS_VN).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
            //X.Msg.Notify("delete", _taskID.ToString()).Show();
        }

        private bool SetValue(Entities.Task entity)
        {
            try
            {
                txtName.Text = entity.TaskName;
                txtNote.Text = entity.Descriptions;
                TaskID.Text = entity.TaskID.ToString();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        private bool SetValue(Entities.TaskTeam entity)
        {
            try
            {
                var teamName = new BusinessLogic.Team().GetTeam(Convert.ToInt32(hiddenTeamID.Text)).Name;
                cbbTeamList.Text = teamName;

                txtStartDate.Value = entity.StartDate;
                txtExpectedEndDate.Value = entity.ExpectedEndDate;
                txtComment.Text = entity.Comments;
                radioStatusDone.Checked = !entity.Status.Equals('I');
                radioStatusWorking.Checked = entity.Status.Equals('I');

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

        protected void btnAddTeam_Click(object sender, DirectEventArgs e)
        {
            if (!String.IsNullOrEmpty(hiddenTaskID.Text))
            {
                _isUpdate = false;
                cbbTeamList.ReadOnly = false;
                radioStatusWorking.Checked = true;
                radioStatusDone.Hidden = true;
                this.windowDetailTeam.Icon = Icon.Add;
                this.windowDetailTeam.Title = _taskName + " - Thêm nhóm";
                this.windowDetailTeam.Show();
            }
        }

        protected void gridTeamList_OnCommand(object sender, DirectEventArgs e)
        {
            var taskID = e.ExtraParams["TaskID"];
            var teamID = e.ExtraParams["TeamID"];
            var taskTeamID = e.ExtraParams["TaskTeamID"];
            var command = e.ExtraParams["Command"];

            this.hiddenTaskID.Text = taskID;
            this.hiddenTeamID.Text = teamID;
            this.hiddenTaskTeamID.Text = taskTeamID;

            if (command.Equals("Edit"))
            {
                _isUpdate = true;
                var obj = new BusinessLogic.TaskTeam();
                var entity = obj.GetTaskTeam(Convert.ToInt32(taskTeamID));

                if (entity != null && string.IsNullOrEmpty(obj.ErrorMessage))
                {
                    if (!this.SetValue(entity))
                    {
                        this.btnSave.Enable(false);
                        X.Msg.Notify(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.TRANSFER_FAILSE_VN + "<BR>" + AuditHelpMessage.PLS_BACK_LASTER).Show();
                    }
                }

                this.cbbTeamList.ReadOnly = true;
                radioStatusDone.Hidden = false;
                this.windowDetailTeam.Icon = Icon.ReportEdit;
                this.windowDetailTeam.Title = "Cập nhật thông tin";
                this.windowDetailTeam.Show();
            }
            else
            {
                X.Msg.Confirm(AuditInfoMessage.AUDIT_TITLE_VN, AuditInfoMessage.DELETE_CONFIRM_VN,
                              new MessageBoxButtonsConfig()
                              {
                                  Yes = new MessageBoxButtonConfig
                                  {
                                      Text = "Xác nhận",
                                      Handler = "Team.List.DeleteTaskTeam()"
                                  },
                                  No = new MessageBoxButtonConfig
                                  {
                                      Text = "Quay lại"
                                  }

                              }).Show();
            }
        }

        [DirectMethod(Namespace = "Team.List", ShowMask = true)]
        public void DeleteTaskTeam()
        {
            if (!String.IsNullOrEmpty(hiddenTaskID.Text) && !String.IsNullOrEmpty(hiddenTeamID.Text))
            {
                var obj = new BusinessLogic.TaskTeam();
                try
                {
                    var entity = new TaskTeam()
                    {
                        TaskTeamID = Convert.ToInt32(hiddenTaskTeamID.Text)
                    };

                    var result = obj.Delete(entity);

                    if (result)
                    {
                        var source = new BusinessLogic.TaskTeam().GetTaskTeamShow(Convert.ToInt32(hiddenTaskID.Text));
                        this.storeTeamList.DataSource = source;
                        this.storeTeamList.DataBind();

                        X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.DELETE_SUCCESS_VN).Show();
                    }
                    else
                    {
                        X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                    }
                }
                catch
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, "Có lỗi xảy ra!").Show();
                }
            }
        }

        protected void gridTask_OnRowSelected(object sender, DirectEventArgs e)
        {
            _taskID = Convert.ToInt32(e.ExtraParams["TaskID"]);
            var taskName = e.ExtraParams["TaskName"];
            _taskName = taskName;

            this.hiddenTaskID.Text = _taskID.ToString();
            this.pnlTeamList.Title = taskName + " - Danh sách phân nhóm";

            var source = new BusinessLogic.TaskTeam().GetTaskTeamShow(Convert.ToInt32(hiddenTaskID.Text));
            if (source != null)
            {
                this.storeTeamList.DataSource = source;
                this.storeTeamList.DataBind();
            }
        }

        protected void storeTeam_OnReadData(object sender, StoreReadDataEventArgs e)
        {
            var store = sender as Store;
            var filter = e.Parameters["query"];
            var start = e.Start;
            var limit = e.Limit;

            int total;

            var source = new BusinessLogic.Team().FilterByName(start, limit, filter, out total);

            if (source != null && source.Any() && total != -1)
            {
                var pagingData = new Paging<Entities.Team>(source, total);

                e.Total = pagingData.TotalRecords;

                store.DataSource = pagingData.Data;
                store.DataBind();
            }
        }

        protected void btnSaveTeam_Click(object sender, DirectEventArgs e)
        {
            var obj = new BusinessLogic.TaskTeam();
            //var tid = cbbTeamList.SelectedItem.Value;
            var entityData = new Entities.TaskTeam()
            {
                TaskID = !String.IsNullOrEmpty(this.hiddenTaskID.Text.Trim()) ? Convert.ToInt32(this.hiddenTaskID.Text) : -1,
                ExpectedEndDate = txtExpectedEndDate.IsEmpty ? null : (DateTime?)txtExpectedEndDate.Value,
                StartDate = txtStartDate.IsEmpty ? null : (DateTime?)txtStartDate.Value,
                Comments = String.IsNullOrEmpty(txtComment.Text.Trim()) ? string.Empty : txtComment.Text.Trim(),
                TeamID = !String.IsNullOrEmpty(this.hiddenTeamID.Text.Trim()) ? Convert.ToInt32(this.hiddenTeamID.Text) : -1,
                TaskTeamID = !String.IsNullOrEmpty(this.hiddenTaskTeamID.Text.Trim()) ? Convert.ToInt32(this.hiddenTaskTeamID.Text) : -1,
                Status = radioStatusWorking.Checked ? 'I' : 'D'
            };

            if (_isUpdate)
            {
                var result = obj.Update(entityData);

                if (result)
                {
                    var source = new BusinessLogic.TaskTeam().GetTaskTeamShow(Convert.ToInt32(hiddenTaskID.Text));
                    this.storeTeamList.DataSource = source;
                    this.storeTeamList.DataBind();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.UPDATE_SUCCESS_VN).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
            else
            {
                entityData.TeamID = Convert.ToInt32(cbbTeamList.SelectedItem.Value);
                var result = obj.AddNew(entityData);

                if (result)
                {
                    var source = new BusinessLogic.TaskTeam().GetTaskTeamShow(Convert.ToInt32(hiddenTaskID.Text));
                    this.storeTeamList.DataSource = source;
                    this.storeTeamList.DataBind();

                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.INSERT_SUCCESS_VN).Show();
                }
                else
                {
                    X.Msg.Notify(SystemInfoMessage.SYS_TITLE_VN, AuditInfoMessage.AUDIT_FAILSE_VN.Replace("{0}", obj.ErrorMessage)).Show();
                }
            }
        }
    }
}